use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::order_return_histories::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub order_return_id: String,
    pub status: String,
    pub notify: i8,
    pub comment: String,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Order Return ID must not be empty."))]
    pub order_return_id: String,
    #[validate(length(min = 1, message = "Status must not be empty."))]
    pub status: String,
    #[validate(length(min = 1, message = "Comment must not be empty."))]
    pub comment: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            order_return_id: self.order_return_id.as_ref().to_owned(),
            status: self.status.as_ref().to_owned(),
            comment: self.comment.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::order_return_histories::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an order return history by the provided id
    ///
    /// # Errors
    ///
    /// When could not find order return history or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let order_return_history = order_return_histories::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_return_histories::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        order_return_history.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds order return histories by the provided order return id
    ///
    /// # Errors
    ///
    /// When could not find order return histories or DB query error
    pub async fn find_by_order_return_id(
        db: &DatabaseConnection,
        order_return_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let order_return_histories = order_return_histories::Entity::find()
            .filter(
                model::query::condition()
                    .eq(
                        order_return_histories::Column::OrderReturnId,
                        order_return_id,
                    )
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_return_histories)
    }

    /// finds order return histories by the provided status
    ///
    /// # Errors
    ///
    /// When could not find order return histories or DB query error
    pub async fn find_by_status(db: &DatabaseConnection, status: &str) -> ModelResult<Vec<Self>> {
        let order_return_histories = order_return_histories::Entity::find()
            .filter(
                model::query::condition()
                    .eq(order_return_histories::Column::Status, status)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(order_return_histories)
    }

    /// Asynchronously creates an order return history and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the order return history into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let order_return_history = order_return_histories::ActiveModel {
            order_return_id: ActiveValue::set(params.order_return_id.to_string()),
            status: ActiveValue::set(params.status.to_string()),
            notify: ActiveValue::set(params.notify),
            comment: ActiveValue::set(params.comment.to_string()),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(order_return_history)
    }

    /// Deletes the order return history
    ///
    /// # Errors
    ///
    /// When could not delete the order return history from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: order_return_histories::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the order return history's status and comment
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_status_and_comment(
        mut self,
        db: &DatabaseConnection,
        status: String,
        comment: String,
    ) -> ModelResult<Model> {
        self.status = ActiveValue::set(status);
        self.comment = ActiveValue::set(comment);
        Ok(self.update(db).await?)
    }

    /// Updates the order return history's notify flag
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_notify(
        mut self,
        db: &DatabaseConnection,
        notify: i8,
    ) -> ModelResult<Model> {
        self.notify = ActiveValue::set(notify);
        Ok(self.update(db).await?)
    }
}
